package com.kyzh.core.viewmodel

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.gushenge.core.beans.Deal
import com.gushenge.core.impls.WealImpl
import com.gushenge.core.listeners.ResultListener
import com.kyzh.core.MyApplication
import com.kyzh.core.R

class DealDynamicViewModel : ViewModel() {

    private val data = MutableLiveData<ArrayList<Deal>>()
    private val text = MutableLiveData<String>()
    private var p = 1
    private var max = 1
    private val load = MutableLiveData<Int>()
    fun setData(arrayList: ArrayList<Deal>) {
        val array = arrayListOf<Deal>()
        array.addAll(getData().value ?: arrayListOf())
        array.addAll(arrayList)
        data.value = array
    }

    fun getData(): MutableLiveData<ArrayList<Deal>> {
        return data
    }


    fun refresh() {
        data.value?.clear()
        p = 1
        Request()
    }

    fun load() {
        if (p > max) {
            setToasts(MyApplication.instance.getString(R.string.noHaveMore))
        } else {
            Request()
        }
    }

    fun loadTimes(): MutableLiveData<Int> {
        return load
    }

    fun setLoadTimes() {
        load.value = loadTimes().value ?: 0 + 1
    }

    fun toast(): MutableLiveData<String> {
        return text
    }

    fun setToasts(word: String) {
        text.value = word
    }

    private fun Request() {
        WealImpl.dealDynamic(p, object : ResultListener {
            override fun success(beans: Any, p: Int, max: Int) {
                beans as ArrayList<Deal>
                this@DealDynamicViewModel.p = p
                this@DealDynamicViewModel.max = max
                setData(beans)
                setLoadTimes()
            }

            override fun error(error: String) {
                setLoadTimes()
                setToasts(error)
            }
        })
    }
}